<?php
namespace app\common;

use dingtalk\User;
use think\Model;

class UserModel extends Model
{
    protected $name = 'user'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /**
     * 同步钉钉部门人员
     */
    public function syncUser($accessToken){
        $DepartmentModel = new DepartmentModel();
        $deptIds = $DepartmentModel->column('id');
        $alllist=[];
        foreach($deptIds as $deptId){
            $response = User::getlist($accessToken,$deptId);
            if($response['errcode']==0) {
                $userlist = $response['userlist'];
                foreach($userlist as $k=>$v){
                    $alllist[$v['userid']]['userid'] = $v['userid'];
                    $alllist[$v['userid']]['mobile'] = $v['mobile'];
                    $alllist[$v['userid']]['workPlace'] = $v['workPlace'];
                    $alllist[$v['userid']]['remark'] = $v['remark'];
                    $alllist[$v['userid']]['is_admin'] = (int)$v['isAdmin'];;
                    $alllist[$v['userid']]['is_boss'] = (int)$v['isBoss'];
                    $alllist[$v['userid']]['is_leader'] = (int)$v['isLeader'];
                    $alllist[$v['userid']]['name'] = $v['name'];
                    $alllist[$v['userid']]['is_active'] = (int)$v['active'];
                    $alllist[$v['userid']]['department'] = implode(',',$v['department']);
                    $alllist[$v['userid']]['position'] = $v['position'];
                    $alllist[$v['userid']]['email'] = $v['email'];
                    $alllist[$v['userid']]['avatar'] = $v['avatar'];
                    $alllist[$v['userid']]['jobnumber'] = $v['jobnumber'];
                    $alllist[$v['userid']]['openid'] = $v['openId'];
                    $alllist[$v['userid']]['dingid'] = $v['dingId'];
                }
            }
        }
        if(!empty($alllist)){
            $this->where('1=1')->delete();
            $this->allowField(true)->saveAll($alllist,false);
        }
        return true;
    }
}